import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  BadRequestException,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException) // 指定处理的异常 HttpException 可以处理所有的异常，但是会影响 ValidatePipe 自定义的错误提示
export class TestFilter<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    let ctx;
    let response: Response;
    const reqMethod = host.getType();
    console.log('请求方式===', reqMethod);

    // 兼容全局的异常处理，包括pipe 自定义的错误提示
    const res = exception.getResponse() as { message: string[] };

    switch (reqMethod) {
      case 'http':
        // 获取不同上下文
        ctx = host.switchToHttp();
        response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        response.status(400).json({
          statusCode: 400,
          message: res?.message?.join
            ? res?.message?.join(',')
            : exception.message,
        });
        break;
      case 'ws':
        // 获取不同上下文
        ctx = host.switchToWs();
        break;
      case 'rpc':
        // 获取不同上下文
        ctx = host.switchToRpc();
        break;
    }
  }
}
